import java.util.Scanner;
import java.util.InputMismatchException;


public class Driver {

	public static void main (String[] args){
		
		//Declaracion de objetos
		Huffman arbol;
		
		//decalracion de variables
		String cadena;
		String[] chart;
		int[] frec;
		String[] letras;
		
		
		//Escojer el uso de stacks o de colas
		System.out.println("\n   HOJA 7 :O)\n");
			
		cadena = (String)obtenerString("ingrese una cadena de caracteres", false);
		
		System.out.println(cadena);
		
		int pos = 0;
		int pos2 = 1;
		
		chart = new String[cadena.length()];
		
		
		for (pos = 0; pos<cadena.length(); pos++){
			chart[pos]= cadena.substring(pos, pos2);
			pos2++;
		}
		
		arbol = new Huffman(chart);   // creamos huffman con chart
		frec = arbol.frecuencia(); 
		arbol.setCodigo(); 
		letras = arbol.getLetras(); 
		frec = ordenar(frec, frec.length, letras);  
		arbol.setletrasfrec(frec, letras);
		System.out.println(arbol.toString());  
		
		
		
		
	}
	
	public static int[]  ordenar(int data[], int n, String letras[] ){
		int numSorted = 1; // number of values in place
		int index; // general index
	
		while (numSorted <  n){
			// take the first unsorted value
			int temp = data[numSorted];
			String temp2 = letras[numSorted];
			// ...and insert it among the sorted:
			for (index = numSorted; index > 0; index--){
				if (temp < data[index-1]){
						data[index] = data[index-1];
						letras[index] = letras[index-1];
						
				} 
				else {
					break;
				}
			}
			// reinsert value
			data[index] = temp;
			letras[index] = temp2;
			numSorted++;
			
		}
		return data;
	}
	public static int[] ordenar2(int data[], int n){
		int numSorted = 1; // number of values in place
		int index; // general index
	
		while (numSorted <  n){
			// take the first unsorted value
			int temp = data[numSorted];
			// ...and insert it among the sorted:
			for (index = numSorted; index > 0; index--){
				if (temp < data[index-1]){
						data[index] = data[index-1];
				} 
				else {
					break;
				}
			}
			// reinsert value
			data[index] = temp;
			numSorted++;
		}
		return data;
	}

	
	//obtener numero
		public static String obtenerString(String mensaje, boolean mostrar){
			Scanner ingreso = new Scanner(System.in);
			String cadena = "";
				
			System.out.print(mensaje);
			try{
				cadena = ingreso.next();
			}
			catch(InputMismatchException exception){
				if (mostrar)
					System.out.println("\nERROR: ~~> Dato invalido. :O(\n");
			}
			finally{
				ingreso.nextLine();//Atrapar el ENTER
			}
			return cadena;
		}
	
}
